package org.qydjk.console.controller.basic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.SingleProject;
import org.qydjk.common.pojo.SingleProjectCategory;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.console.vo.SingleProjectBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lanan on 2017/12/11 0011.
 */

@Controller
@RequestMapping("/single/project")
public class SingleProjectController extends BaseController {

    /**
     * 单项库跳转
     * @author Lanan
     * @time 2017.12.12
     * @return 跳转地址
     */
    @RequestMapping("/category.do")
    public String singleProjectCategory() {
        return "basic/singleProject/singleProjectCategory";
    }



    /*****************************   单项库部分   ******************************/
    /**
     * 获取单项库分类列表
     * @author Lanan
     * @time 2017.12.12
     */
    @RequestMapping("/category/list.do")
    @ResponseBody
    public Object singleProjectCategoryList(SingleProjectCategory category, int page, int rows) {
        List<SingleProjectCategory> singleProjectCategories = new ArrayList<SingleProjectCategory>();
        try {
            String sql = "select * from qy_single_project_category";
            String totalSql = "select count(id) from qy_single_project_category";
            if (!StringUtil.isEmptyOrNull(category.getName())) {
                sql = sql + " where name like '%"+ category.getName() +"%'";
                totalSql = totalSql + " where name like '%"+ category.getName() +"%'";
            }
            if (category.getStatus() != null && !StringUtil.isEmptyOrNull(category.getStatus().toString())) {
                int result1 = sql.indexOf("where");
                if (result1 != -1) {
                    // 含 where
                    sql = sql + " and status=" + category.getStatus();
                    totalSql = totalSql + " and status=" + category.getStatus();
                } else {
                    // 不含 where
                    sql = sql + " where status=" + category.getStatus();
                    totalSql = totalSql + " where status=" + category.getStatus();
                }
            }
            sql = sql + " order by ord desc";
            singleProjectCategories = baseService.findBySQL(sql, SingleProjectCategory.class, new HibernatePage(page, rows));
            int total = baseService.getRecordCountSQL(totalSql);
            return new EasyUIResponse(total, singleProjectCategories);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new EasyUIResponse(0, singleProjectCategories);
    }

    /**
     * 保存单项类
     * @author Lanan
     * @time 2017.12.12
     */
    @RequestMapping("/categary/insert.do")
    @ResponseBody
    public Object insertSingleProjectCategray(SingleProjectCategory category) {
        category.setStatus(0);
        return handleSaveOrUpdate(true, category, "保存");
    }

    /**
     * 更新单项类
     * @author Lanan
     * @time 2017.12.12
     */
    @RequestMapping("/categary/update.do")
    @ResponseBody
    public Object updateSingleProjectCategray(SingleProjectCategory category) {
        return handleSaveOrUpdate(false, category, "修改");
    }

    /**
     * 删除单项类
     * @author Lanan
     * @time 2017.12.12
     */
    @RequestMapping("/categary/delete.do")
    @ResponseBody
    public Object deleteSingleProjectCategray(SingleProjectCategory category) {
        return handleDelete(category.getId(), category, true);
    }

    /**
     * 处理添加和修改
     * @author Lanan
     * @time 2017.12.13
     *
     * @param isSave 是否是添加
     * @param msg 前台提示信息
     */
    private Object handleSaveOrUpdate(Boolean isSave, Object object, String msg) {
        Object tempObject = new Object();
        Object tempUda = new Object();
        if (object.getClass().isAssignableFrom(SingleProjectCategory.class)) {
            SingleProjectCategory singleProjectCategory = (SingleProjectCategory) object;
            if (isSave) singleProjectCategory.setCreateTime(new Date());
            singleProjectCategory.setUpdateTime(new Date());
            tempObject = singleProjectCategory;
            if (!isSave) {
                try {
                    SingleProjectCategory uda = baseService.get(SingleProjectCategory.class, singleProjectCategory.getId());
                    tempUda = uda;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (object.getClass().isAssignableFrom(SingleProject.class)) {
            SingleProject singleProject = (SingleProject) object;
            if (isSave) singleProject.setCreateTime(new Date());
            singleProject.setUpdateTime(new Date());
            tempObject = singleProject;
            if (!isSave) {
                try {
                    SingleProject uda = baseService.get(SingleProject.class, singleProject.getId());
                    tempUda = uda;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        JSONObject resp = new JSONObject();
        try {
            if (isSave) {
                baseService.save(tempObject);
            } else {
                BeanUtil.copyProperties(tempObject, tempUda);
                baseService.update(tempUda);
            }
            resp.put("success", true);
            resp.put("msg", msg);
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }

    /**
     * 单项分类启用禁用
     * @param id
     * @param status
     * @return
     */
    @RequestMapping("/changeCategoryStatusToEnableOrDisable.do")
    @ResponseBody
    private Object changeCategoryStatusToEnableOrDisable(Integer id, Integer status) {
        JSONObject resp = new JSONObject();
        try {
            SingleProjectCategory singleProjectCategory = baseService.get(SingleProjectCategory.class, id.intValue());
            singleProjectCategory.setStatus(status);
            singleProjectCategory.setUpdateTime(new Date());
            if (status == 0) {
                Date date = new Date();
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sf.format(date);
                String sql = "UPDATE qy_single_project SET `status`='0', update_time = '" + dateStr + "' WHERE `status` = '1' AND single_project_category_id = '" + id.intValue() + "'";
                baseService.excuteSQL(sql);
            }
            baseService.update(singleProjectCategory);
            resp.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }



    /*****************************   单项部分   ******************************/
    /**
     * 获取单项列表
     * @author Lanan
     * @time 2017.12.12
     */
    @RequestMapping("/selectApply.do")
    @ResponseBody
    public Object selectApply(SingleProject singleProject, int page, int rows) {
        List<SingleProject> singleProjects = new ArrayList<SingleProject>();
        String sql = "select p.*,pc.name as single_project_category_name from qy_single_project p left join qy_single_project_category pc on p.single_project_category_id = pc.id where 1 = 1 ";
        String countSql = "select count(p.id) from qy_single_project p left join qy_single_project_category pc on p.single_project_category_id = pc.id  where 1 = 1 ";
        if (singleProject.getSingleProjectCategoryId() != null) {
            String whereStr = " and p.single_project_category_id = " + singleProject.getSingleProjectCategoryId().intValue();
            sql += whereStr;
            countSql += whereStr;
        }
        if (!StringUtil.isEmptyOrNull(singleProject.getName())) {
            sql += " and p.name like '%"+ singleProject.getName() +"%'";
            countSql += " and p.name like '%"+ singleProject.getName() +"%'";
        }
        if (singleProject.getStatus() != null && !StringUtil.isEmptyOrNull(singleProject.getStatus().toString())) {
            sql += " and p.status=" + singleProject.getStatus();
            countSql +=  " and p.status=" + singleProject.getStatus();
        }
        sql += " order by p.ord desc";
        try {
            singleProjects = baseService.findBeanBySQL(sql,SingleProjectBean.class, new HibernatePage(page, rows));
            int total = baseService.getRecordCountSQL(countSql);
            return new EasyUIResponse(total, singleProjects);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new EasyUIResponse(0, singleProjects);
    }

    /**
     * 添加单项信息
     * @author Lanan
     * @time 2017.12.13
     */
    @RequestMapping("/insert.do")
    @ResponseBody
    public Object insertSingleProject(SingleProject category, String singleProjectCategoryId) {
        JSONObject resp=new JSONObject();
        if (StringUtil.isEmptyOrNull(singleProjectCategoryId)) {
            resp.put("success", false);
            resp.put("msg", "请选择正确的单项分类！");
            return JSON.toJSON(resp);
        }
        category.setStatus(0);
        return handleSaveOrUpdate(true, category, "保存");
    }

    /**
     * 修改单项信息
     * @author Lanan
     * @time 2017.12.13
     */
    @RequestMapping("/update.do")
    @ResponseBody
    public Object updateSingleProject(SingleProject category) {
        return handleSaveOrUpdate(false, category, "修改");
    }

    /**
     * 删除单项信息
     * @author Lanan
     * @time 2017.12.13
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object delectSingleProject(SingleProject category) {
        return handleDelete(category.getId(), category, false);
    }

    /**
     * 处理删除
     * @author Lanan
     * @time 2017.12.13
     * @param isNeedAnotherWhere 是否需要添加判断条件 当删除单项类时需要判断该类下是否还有单项
     */
    private Object handleDelete(Integer id, Object object, Boolean isNeedAnotherWhere) {
        JSONObject resp = new JSONObject();
        try {
            if(id == null || id == 0){
                resp.put("success", false);
                resp.put("msg", "id不能为空！");
                return JSON.toJSON(resp);
            }
            if (isNeedAnotherWhere) {
                String countSql = "select count(id) from qy_single_project where single_project_category_id=" + id;
                int total = baseService.getRecordCountSQL(countSql);
                if (total > 0) {
                    resp.put("success", false);
                    resp.put("msg", "因含单项，该单项类不能删除！");
                    return JSON.toJSON(resp);
                }
            }
            resp.put("success", true);
            baseService.delete(object);
        } catch (Exception e) {
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }

    /**
     * 获取单项Combobox
     * @author Lanan
     * @time 2017.12.13
     */
    @RequestMapping("/getSingleProjectCategoryCombobox.do")
    @ResponseBody
    public Object getSingleProjectCategoryCombobox() {
        try {
            List<SingleProjectCategory> list = baseService.findByHql("from SingleProjectCategory order by ord desc");
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 启用与禁用操作单项
     * @param ids
     * @param status
     * @return
     */
    @RequestMapping("/changeSingleStatusToEnableOrDisable.do")
    @ResponseBody
    private Object changeSingleStatusToEnableOrDisable(String ids, Integer status) {
        JSONObject resp = new JSONObject();
        try {
            String sql;
            Date date = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = sf.format(date);
            if (status == 1) {
              sql = "UPDATE qy_single_project sp SET sp.`status` = '1', sp.update_time = '" + dateStr + "' " +
                      "WHERE sp.`status` = '0' " +
                      "AND sp.id in (" + ids + ") " +
                      "AND exists (SELECT spc.id FROM qy_single_project_category spc " +
                      "WHERE sp.single_project_category_id = spc.id AND spc.`status` = '1')";
            } else {
                sql = "UPDATE qy_single_project sp SET sp.`status` = '0', sp.update_time = '" + dateStr + "' " +
                        "WHERE sp.`status` = '1' " +
                        "AND sp.id in (" + ids + ") ";
            }
            baseService.excuteSQL(sql);
            resp.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }


}
